package com.haohuo.framework.email;

import com.haohuo.framework.mojo.MailParamsVo;
import com.haohuo.framework.utils.DecryptUtil;
import org.codehaus.plexus.util.StringUtils;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 *
 * Copyright https://wtfu.site Inc. All Rights Reserved.
 *
 * @date 2023/1/7
 *                          @since  1.0
 *                          @author 12302
 *
 */
public class MailTax {

    public static void sendMailWithAttachFile(MailParamsVo paramsVo){
        String pwd = paramsVo.getPwd();
        if(DecryptUtil.isEncrypt(pwd)){
            String master = DecryptUtil.decodeMaster();
            if(StringUtils.isEmpty(master)){
                master = "xhs12302";
            }
            pwd = DecryptUtil.decodeSlaver(pwd, master);
        }

        String server = paramsVo.getSmtp();
        String to = paramsVo.getTo();
        String from = paramsVo.getFrom();
        // 参数配置
        Properties props = new Properties();
        // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.transport.protocol", "smtp");
        // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.host", server);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        Session mailSn=Session.getDefaultInstance(props);
        //使Debug模式为真，可以查看交互消息。
        mailSn.setDebug(false);
        try {
            MimeMessage message=new MimeMessage(mailSn);
            //设置消息
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //message.addRecipient(Message.RecipientType.CC, new InternetAddress("512751300@qq.com"));
            message.setSubject("MVN PLUGIN REPORT");
            //message.setText("HelloWorld,this is a jsp Email!");
            Multipart mp = new MimeMultipart();

            Map<Boolean, List<File>> collect = paramsVo.getFiles().stream().collect(Collectors.groupingBy(File::exists));
            if(collect.get(false) == null){collect.put(false,new ArrayList<>());}
            if(collect.get(true) == null){collect.put(true,new ArrayList<>());}

            List<String> notList = collect.get(false).stream().map(File::getAbsolutePath).collect(Collectors.toList());

            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent("details see attach files\n\n not exist files: \n" + notList, "text/plain;charset=GBK");
            mp.addBodyPart(mbpContent);

            for (File item : collect.get(true)) {
                MimeBodyPart body = new MimeBodyPart();
                body.attachFile(item);
                body.setFileName(MimeUtility.encodeText(item.getName()));
                mp.addBodyPart(body);
            }
            message.setContent(mp);
            message.saveChanges(); //

            Transport transport = mailSn.getTransport("smtp");
            transport.connect(server, from, pwd);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) { e.printStackTrace();}
    }
}
